<template>
	<div class="view">
		<transition name='page-switch'>
			<div class="loginBox" v-if="typeLink == 1">
				<div class="login-title">
					<h1>验证码登录</h1>
					<p>您需要验证您的<span>师生通账号</span>才能完成报名流程</p>
				</div>
				<div class="input_box">
					<input type="tel" @keyup="addSpace" v-model="inputvalue" maxlength="13" pattern=[0-9]* placeholder="请输入手机号" oninput="if(value.length > 13) value = value.slice(0, 13)" />
					<div class="em_box" v-if="inputvalue.length!=0" @click="clear"></div>
				</div>
				<div class="login-go" :class="{'logingo-ok':isGoSend}" @click="sendCode"></div>
			</div>
		</transition>
		<transition name='page-switch'>
			<div class="loginBox" v-if="typeLink == 2" @click="focusCode">
				<div class="login-title">
					<h1>输入验证码</h1>
					<p>验证码已发送至 <span>{{phone}}</span></p>
				</div>
				<div class="check-input">
                    <ul class='num-list u-flex_row'>
                        <li class='num-box left' v-for="(item,index) in boxList" :key="index">
                            <div class="cursor" v-if="checkNum.length===index"></div>
                            <div class="num" v-if="checkNum.length>=index+1">{{checkNum[index]}}</div>
                        </li>
                    </ul>
                    <input ref="codeInput" class='check-num' type='number' v-model="checkNum" maxlength='6' pattern=[0-9]* focus='true' auto-focus='true' oninput="if(value.length > 6) value = value.slice(0, 6)">
                </div>
				<div class="btn-send">
					<i v-show="countdown>0">重新获取（{{countdown}}s）</i>
                    <span v-show="countdown==0" @click="sendCode">重新获取</span>
				</div>
				<div class="login-go" :class="{'logingo-ok':checkNum.length==6,'login-loading':isLoading}" @click="goLogin"><i></i></div>
			</div>
		</transition>
	</div>
</template>

<script>
import * as api from '@/api/index';
import { debounce} from '@/utils/common.js'
export default {
	data(){
		return{
			typeLink: 1,					//1：输入手机号  2：输入验证码
			inputvalue: '',
			reguP: /^[1][3,4,5,6,7,8,9][0-9]{9}$/,
			isGoSend: false,
			phone: '',
			boxList: Array(6),
			checkNum: '',					//验证码
			countdown: 60,   //倒计时
			timeLoop: null,
			isLoading: false,
			token:"",
			userInfo:{},
		}
	},
	created(){
		window.localStorage.clear()
		window.sessionStorage.clear()
		this.getInit()
	},
	mounted(){
		
	},
	watch:{
		inputvalue(data){
			let phoneNum = data.replace(/\s*/g,'');		//去除所有空格
			var len = phoneNum.length;
			if(len === 11 )	this.isGoSend = true		//验证是否是手机号码
		},
	},
	methods:{
		// 获取授权token
		async getInit(){
			var data = {
				userName:"poetrygame",
				password:"12345678910",
			}
			var res = await api.getToken(data)
			if(res.resultCode == 1){
				this.token = res.value
				this.$store.dispatch("setToken",this.token)
				window.localStorage.setItem('TokenKey',this.token)
			}else
				this.$LayerTips({
					content: res.exceptions,
					time: 1500
				});
		},

		addSpace(e){
			var _phoneNum = this.inputvalue.trim(),					//去除首尾空格
				phoneNum = this.inputvalue.replace(/\s*/g,'');		//去除所有空格
			this.inputvalue = this.inputvalue.replace(/[^\d\s]/g,'')	//只能输入数字与空格

			this.isGoSend = false
			if (e.keyCode === 8) {					//点击删除键，删除与之相邻的空格
				this.inputvalue = _phoneNum;
				return;
			}
			var len = phoneNum.length;
			if (len === 3 || len === 7) {				//格式--133 1111 1111
				this.inputvalue += ' ';
			}
			if(len === 11 )	this.isGoSend = true		//验证是否是手机号码
		},
		clear(){
			this.isGoSend = false
			this.inputvalue=''
		},
		async sendCode(){
			if(this.isGoSend){
				if(this.typeLink = 1){				
					this.phone = this.inputvalue.replace(/\s*/g,'')
					if(!this.reguP.test(this.phone) ){
						this.$LayerTips({
							content:"手机号输入错误",
							time: 1500
						});  
						return false
					}
				}
				this.phone = this.inputvalue.replace(/\s*/g,'')
				var data = {
					mobile: this.phone
				}
				var res = await api.getVerificationCode(data)
				if(res.resultCode == 1){
					this.typeLink = 2
					this.focusCode()
					this.checkNum = ''
					this.countdown = 60
					
					clearInterval(this.timeLoop)
					this.timer()
				}else{
					this.$LayerTips({
						content: res.resultMessage,
						time: 1500
					});  
				}	
			}
		},
		focusCode(){
			this.$nextTick(()=>{ 
				this.$refs.codeInput.focus();
			})
		},
		// 登陆
		async goLogin(){
			this.isLoading = true
			var data = {
				mobile: this.phone,
				code: this.checkNum,
				wxOpenId:'1'
			}
			var res = await api.login(data)
			if(res.resultCode == 1){
				this.isLoading = false
				localStorage.setItem("rolesList",JSON.stringify(res.value));
				if(res.value.length == 1){
					this.userInfo = res.value[0];
					localStorage.setItem("userId",this.userInfo.userId);
					this.$store.dispatch("setUserId",this.userInfo.userId)
					this.getUserInfo()
					return false
				}
				
				this.$router.replace({path:'/roles'});
			}else{
				this.isLoading = false
				this.$LayerTips({
					content: res.resultMessage,
					time: 1500
				});  
			}
		},
		/*****
		 * 获取活动信息
		 * sstUserType: 1管理 2教师 3学生
		 * stagesType: 1报名 2初赛 3复赛
		 * ****/ 
        async getUserInfo(){
			var data = {
                userId: this.userInfo.userId
			}
			var res = await api.getUserInfo(data)
			if(res.resultCode == 1){
				let resVal =  res.value
				localStorage.setItem("userInfo",JSON.stringify(resVal));
				if(resVal.stagesType == 1) this.$router.replace({path:'/signup'});	
				if(resVal.stagesType == 2) this.$router.replace({path:'/preliminary'});
			}
		},
        /* 计时器 */
        timer(){
            this.timeLoop=setInterval(()=>{
                if(this.countdown>0) this.countdown--;
                else clearInterval(this.timeLoop)
            }, 1000);
		},
		
	}
}
</script>

<style lang="scss" scoped>

</style>
